package com.huiyeji.dynamic.core.provider;

import com.huiyeji.dynamic.core.DynamicContext;

import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringParamProvider extends AbstractParamProvider {

    private static final Pattern REPLACE_PATTERN = Pattern.compile("\\$\\{(.*?)\\}");

    public StringParamProvider(String paramName) {
        super(paramName.substring(1, paramName.length()-1));
    }

    @Override
    public Object get(DynamicContext context, String paramName) {
        String realParamName = paramName.replace("<#1>", ",")
                .replace("<#2>","'");
        return replaceString(context, realParamName);
    }

    private String replaceString(DynamicContext context, String text){
        if (text == null || "".equals(text)){
            return "";
        }
        Matcher matcher = REPLACE_PATTERN.matcher(text);
        HashSet<String> set = new HashSet<String>();
        while (matcher.find()){
            set.add(matcher.group(1));
        }
        if (set.size()>0){
            for (String s : set) {
                Object object = context.getObject(s);
                text = text.replaceAll("\\$\\{" + s + "}", object == null?"":object.toString());
            }
        }
        return text;
    }
}
